package com.liuhangkai.firstpro.middle;

import com.liuhangkai.firstpro.config.CustomException;
import com.liuhangkai.firstpro.config.EnforcerFactory;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author : yx-0176
 * @description
 * @date : 2021/1/20
 */
@WebFilter(urlPatterns = "/*" , filterName = "JCasbinAuthzFilter")  //  /**
@Order(Ordered.HIGHEST_PRECEDENCE)//执行顺序，最高级别最先执行，int从小到大
public class JCasbinAuthzFilter implements Filter {


    private EnforcerFactory enforcer;

    @Autowired
    public JCasbinAuthzFilter(EnforcerFactory enforcer){
        this.enforcer = enforcer;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器初始化");
    }

    @Autowired
    @Qualifier("handlerExceptionResolver")
    private HandlerExceptionResolver resolver;
    @SneakyThrows
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain){
        System.out.println("过滤器初始化");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String user = request.getParameter("username");
        String path = request.getRequestURI();
        String method = request.getMethod();
        System.out.println("============");
        System.out.println(user);
        System.out.println(path);
        System.out.println(method);
        if (!enforcer.enforce(user, path, method)) {
           // throw new Exception("无权访问7");
            resolver.resolveException(request, response, null, new CustomException("无法访5问",10023));
            return;
        }else{
            servletRequest.setAttribute("flag","zhangsan");
            chain.doFilter(request, response);
        }



    }

    @Override
    public void destroy() {

    }

}
